package com.csw.android.androidtest.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.csw.android.androidtest.R;

import java.util.ArrayList;
import java.util.List;

public class LogView extends FrameLayout {

    private List<Object> data = new ArrayList<>();
    private BaseQuickAdapter<Object, BaseViewHolder> logAdapter;

    public LogView(@NonNull Context context) {
        this(context, null);
    }

    public LogView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LogView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        RecyclerView recyclerView = new RecyclerView(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        addView(recyclerView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        logAdapter = new BaseQuickAdapter<Object, BaseViewHolder>(R.layout.item_log, data) {
            @Override
            protected void convert(BaseViewHolder helper, Object item) {
                helper.setText(R.id.textView, item.toString());
            }
        };
        recyclerView.setAdapter(logAdapter);
    }

    public void addLog(Object log) {
        synchronized (this) {
            data.add(log);
        }
        post(new Runnable() {
            @Override
            public void run() {
                logAdapter.notifyItemInserted(data.size());
            }
        });
    }

    public void clearLog() {
        synchronized (this) {
            data.clear();
        }
        post(new Runnable() {
            @Override
            public void run() {
                logAdapter.notifyDataSetChanged();
            }
        });
    }
}
